// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue';
import App from './App';
import store from './store';
import router from './router';
import './common/stylus/index.styl';
import axios from 'axios';
import VueAxios from 'vue-axios';
import Vuex from 'vuex';
import {Utils} from '@/utils/utils.js';
import VueLazyload from 'vue-lazyload';
import MintUI from 'mint-ui';
import 'mint-ui/lib/style.css';
import 'vue-ydui/dist/ydui.base.css';
// 初始化组件
Vue.use(VueLazyload, {
  preLoad: 2,
  loading: require('./assets/loading.gif'),
  error: require('./assets/error.jpg'),
  attempt: 1
});
//  初始化插件
Vue.config.productionTip = false;
Vue.use(MintUI);
Vue.use(VueAxios, axios);
Vue.use(Vuex);

// 配置axios
axios.defaults.timeout = 30000;
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';
axios.defaults.baseURL = 'http://zlilionmall.chinacloudsites.cn/Api';
// axios请求拦截
// 拦截请求
axios.interceptors.request.use((config) => {
  let jwt = Utils.GetJwt();
  if (jwt) {
    config.params = {token: jwt};
  }
  return config;
}, (error) => {
  return Promise.reject(error);
});

// 拦截返回
axios.interceptors.response.use((res) => {
  return res;
}, (error) => {
  if (!error.response) {
    router.push({name: 'error'});
  } else {
    if (error.response.status === 401) {
      Utils.RemoveJwt();
      router.push({name: 'customerror', query: {errdesc: 'Jwt验证失败,请重新打开页面!'}});
    } else {
      if (error.response.status === 404) {
        router.push({name: 'error'});
      } else {
        router.push({name: 'customerror', query: {errdesc: error.message}});
      }
    }
  }
  return Promise.reject(error);
});

// 定义路由全局钩子,控制导航栏是否显示
router.beforeEach((to, from, next) => {
  // 超过两层路由则需要隐藏导航栏
  if (to.matched.length > 2) {
    store.commit('HIDE_NAVBAR');
  } else {
    store.commit('VIS_NAVBAR');
  }
  next();
});

let app = new Vue({
  el: '#app',
  store,
  router,
  template: '<App/>',
  components: {App}
});
// 全局错误处理
Vue.config.errorHandler = (err, vm, info) => {
  if (err) {
    console.error(err.stack);
  }
  console.log(arguments);
};
export default app;

